<template>
  <div class="p-4 h-full neo-card neo-border relative">
    <h2 class="text-lg font-semibold mb-2 text-center title-neo">本月人员完成情况</h2>

    <div class="overflow-x-auto w-full">
      <table class="w-full text-sm min-w-max table-fixed">
        <thead class="text-blue-200/80 border-white/10 bg-white/5">
        <tr>
          <th class="py-2 px-3 text-left font-medium whitespace-nowrap">人员</th>
          <th class="py-2 px-3 text-center font-medium whitespace-nowrap">总工单</th>
          <th class="py-2 px-3 text-center font-medium whitespace-nowrap">已完成</th>
          <th class="py-2 px-3 text-center font-medium whitespace-nowrap">完成率</th>
          <th class="py-2 px-3 text-center font-medium whitespace-nowrap sm:hidden md:table-cell">平均评分</th>
        </tr>
        </thead>
        <tbody class="divide-y divide-white/10">
        <tr
            v-for="(person, index) in personnel"
            :key="index"
            class="border-b border-white/10 hover:bg-blue-900/10 transition-colors"
        >
          <td class="py-2 px-3 text-blue-300 truncate max-w-xs">{{ person.name }}</td>
          <td class="py-2 px-3 text-center text-blue-300">{{ person.total }}</td>
          <td class="py-2 px-3 text-center text-yellow-200">{{ person.completed }}</td>
          <td class="py-2 px-3 text-center text-cyan-300">{{ person.completionRate }}%</td>
          <td class="py-2 px-3 text-center text-green-300 sm:hidden md:table-cell">{{ person.rating }}</td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'

const props = defineProps({
  personnel: Array
})
const personnel = ref([])
let refreshInterval = null

const fetchPersonnel = async () => {
  try {
    const res = await axios.get('/api/Notice/GetCompletionRate')
    if (res.data.isSuccess) {
      const newData = res.data.data.map(item => ({
        name: item.userName,
        total: item.totalOrders,
        completed: item.completedOrders,
        completionRate: (item.completionRate * 100).toFixed(2),
        rating: item.rating
      }))
      // 无感刷新：仅在数据变化时替换
      const oldStr = JSON.stringify(personnel.value)
      const newStr = JSON.stringify(newData)
      if (oldStr !== newStr) {
        personnel.value = newData
      }
    }
  } catch (error) {
    console.error('获取人员完成率失败:', error)
  }
}

onMounted(async () => {
  await fetchPersonnel()
  refreshInterval = setInterval(fetchPersonnel, 3000)
})

onBeforeUnmount(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }
})
</script>